package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread {
	private Socket socket;
	private ServerManager parent;
	volatile boolean working;
	private PrintWriter out;
	
	public ServerThread(Socket socket, ServerManager parent, ThreadGroup group) {
		super(group, "ServerThread");
		this.socket = socket;
		this.parent = parent;
		this.working = true;
		this.start();
	}
	
	public void kill() { working = false; }
	
	public void run() {
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			String inputLine, outputLine, client;
			client = socket.getInetAddress().getHostName();
			
			out.println(parent.getWelcomeMessage());
			parent.printToThreads(client+" has joined");
			
			while (working && (inputLine = in.readLine()) != null) {
			    outputLine = client+" said: "+inputLine;
				System.out.println(outputLine);
			    parent.printToThreads(outputLine);
				if (inputLine.equals("exit")) {
					System.out.println(client+" called a shutdown");
					break;
				}	
			}
			
			out.close();
			in.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		parent.shutdown();
	}
	
	public void printExternal(String text) {
		out.println(text);
	}
}
